/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Analysis;

import L2win.L2win;
import Unit.Element;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Arrays;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;


/**
 *
 * @author tuyentran
 */
public class Astar {

    private ArrayList<Element> AGENDA;
    private ArrayList<Element> CHART;
    private L2win laco;
    private int n;
    
    private ArrayList<String> cumTu;

  
    public Astar(String inputFile, boolean flag) throws IOException, ClassNotFoundException, XMLStreamException {
        AGENDA = new ArrayList<Element>();
        CHART = new ArrayList<Element>();
        laco = new L2win();
        initByString(inputFile);
        analysis();
    }
  
    public ArrayList<String> getCumTu() {
        return cumTu;
    }

    private void initByString(String content) throws IOException {
        VietTokenAndTag.run(content); // token and tag for the inputFile, outputFile = inputFile +".dat"
        
        String inputFile = "e://tuyentran-out.txt";
        BufferedReader bfr = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), "utf-8"));
        String str = "";
        int index = 0;
        
        // Tao moi mang de chua cac cum tu tra ve
        cumTu = new ArrayList<String>();
        
        while ((str = bfr.readLine()) != null) {
            if (!str.startsWith("﻿")) {
                index++;
                String[] parts = str.split("\t");
                if (parts.length >= 2)
                    cumTu.add(parts[1]);
                
                Element word = new Element(parts[1], index, index+ 1);
                Element taggedWord = new Element(parts[0], index, index + 1);
                taggedWord.addChild(word);
                AGENDA.add(taggedWord);

                // <editor-fold desc="add label created by single-rule">
                if (parts[0].equals("N") || parts[0].equals("P")) {
                    Element e = new Element("NP", index, index + 1);
                    e.addChild(taggedWord);
                    AGENDA.add(e);
                }
                // </editor-fold>
            }
        }
        n = index;
        System.out.println("câu được tách thành "+n + " cụm từ");
        
        bfr.close();

    }
    
    public int getSoCumTu(){
        return n;
    }
    /**
     * @return return the max-score candidate in AGENDA
     */
    private int maxCandidate() {
        if (!AGENDA.isEmpty()) {
            int max = 0;
            for (int i = 1; i < AGENDA.size(); i++) {
                Element e = AGENDA.get(i);
                if (e.getInside() > AGENDA.get(max).getInside()) {
                    max = i;
                }
            }
            return max;
        } else {
            return -1;
        }
    }

    /**
     * @param e
     * @return check whether e is result or not
     */
    private boolean isResult(Element e) {
        boolean label = (e.getLabel().equals("S"));
        boolean start = (e.getStart() == 1);
        boolean end = (e.getEnd() == (n + 1));
        return (label && start && end);
    }

    /**
     * @function display tree with root e
     *
     * @param e
     */
    private void display(int tab, Element e, XMLStreamWriter writer) throws XMLStreamException {
        boolean hasChild = e.getChildren().size() > 0;
        
        if (hasChild)
            writer.writeStartElement("W");                
     
        String fp = nomalizeLabel(e.getFullLabel(e));
        if (!fp.contains(e.getLabel()))
            fp = e.getLabel() + " [" + e.getFullLabel(e) + "]";
   
       // System.out.println(fp);
        if (hasChild) {
            writer.writeCharacters(nomalizeLabel(fp));    
            System.out.println("-> " + nomalizeLabel(fp));
        }
        
        ArrayList<Element> children = e.getChildren();
        for (int i = 0; i < children.size(); i++) {
            Element child = children.get(i);
            display(tab + 1, child, writer);
        }
        
        if (hasChild)
            writer.writeEndElement();
    }

    private String nomalizeLabel(String label) {
        // TODO: Lam sau
        String result = label.trim();
        
        while(result.contains("  "))
        {
            result = result.replace("  ", " ");
        }
        return result;
    }
    /**
     * @function main analysis
     */
    private void analysis() throws IOException, XMLStreamException {
        DecimalFormat df = new DecimalFormat("#.###");

        boolean stop = false;
        Element result = null;
        while ((!stop) && (!AGENDA.isEmpty())) {
            int indexMax = maxCandidate();

            Element cand = AGENDA.remove(indexMax);

            ArrayList<Element> formedElems = laco.getFormedElements(cand, CHART);
            for (int i = 0; i < formedElems.size(); i++) {
                Element e = formedElems.get(i);
                if (isResult(e)) {
                    stop = true;
                    result = e;
                }
                AGENDA.add(e);
            }

            CHART.add(cand);
        }
        if (stop == false) {
            System.out.println("KHÔNG PHÂN TÍCH ĐƯỢC");
            
        } else {
            System.out.println("PHÂN TÍCH ĐƯỢC");
            
            String outputPathFile = "e://tuyentran-out.xml";
            XMLOutputFactory factory;
            XMLStreamWriter writer;
            factory = XMLOutputFactory.newInstance();
            writer = factory.createXMLStreamWriter(new FileOutputStream(outputPathFile), "utf-8");
        
            // Write start
            writer.writeStartDocument();
         //   writer.writeStartElement("root");
           writer.writeStartElement("sentence");
           // Write body
            display(0, result, writer);
            
            // Write end
           writer.writeEndElement();
           writer.writeEndDocument();
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, XMLStreamException {
    //    Astar astar = new Astar(System.getProperty("user.dir") + "/input.txt");
    }
}
